package top.lilele.adminSystem.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import top.lilele.adminSystem.entity.AdminLogEntity;
import top.lilele.adminSystem.entity.AdminProjectEntity;
import top.lilele.adminSystem.entity.AdminUserEntity;
import top.lilele.adminSystem.mapper.AdminLogMapper;
import top.lilele.adminSystem.mapper.AdminUserMapper;
import top.lilele.adminSystem.numEnum.LogEnum;

import javax.annotation.Resource;

/**
 * @author lilele
 */
@Service
public class AdminLogService {
    @Resource
    AdminLogMapper adminLogMapper;

    @Resource
    AdminUserMapper adminUserMapper;

    @Async("asyncTaskExecutor")
    public void add(String userId, String content, Integer type, String belongId) {
        AdminUserEntity adminUserEntity = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUserEntity>().eq(AdminUserEntity::getId, userId));
        AdminLogEntity adminLogEntity = new AdminLogEntity();
        adminLogEntity.setBelongId(belongId);
        adminLogEntity.setContent("【" + adminUserEntity.getTrueName() + "】" + content);
        adminLogEntity.setType(type);
        adminLogMapper.insert(adminLogEntity);
    }

    /**
     * 录入项目信息日志
     *
     * @param logEntity
     * @param userId
     * @param logEnum
     * @param adminProjectEntity
     */
    @SneakyThrows
    @Async("asyncTaskExecutor")
    public void add(AdminLogEntity logEntity, String userId, LogEnum logEnum, AdminProjectEntity adminProjectEntity) {
        String loginTrueName = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUserEntity>().eq(AdminUserEntity::getId, userId)).getTrueName();
        logEntity.setCreatedId(userId);
        String content = "";
        AdminProjectEntity projectInfo = new ObjectMapper().readValue(logEntity.getContent(), AdminProjectEntity.class);
        // 新增项目
        if (logEnum.getType().equals(LogEnum.ADD_PROJECT.getType())) {
            content = "【" + loginTrueName + "】" + LogEnum.ADD_PROJECT.getMessage() +
                    "：名称（编号）<b>" + projectInfo.getName() + "（" + projectInfo.getNumber()
                    + "）</b>";
        }
        //编辑项目
        else if (logEnum.getType().equals(LogEnum.UPDATE_PROJECT.getType())) {
            content = "【" + loginTrueName + "：" + LogEnum.UPDATE_PROJECT.getMessage() + "]    更新数据：" + logEntity.getContent() + "原数据：" + new ObjectMapper().writeValueAsString(adminProjectEntity);
        }
        logEntity.setContent(content);
        logEntity.setType(logEnum.getType());
        adminLogMapper.insert(logEntity);
    }
}
